import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/header.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class Electricity extends StatefulWidget {
  final Map info;
  const Electricity({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _ElectricityState();

}

class _ElectricityState extends State<Electricity> {

  int _electricQuantity = 0;

  void _refresh() async {
    Map<String, dynamic> params = {
      "lockId": widget.info["lockId"],
      "lockData": widget.info["lockData"],
    };
    EasyLoading.show();
    await lockApi.updateLockData(params);
    Map resData = await lockApi.getLockInfo(widget.info["lockId"]);
    setState(() {
      Map lockInfo = jsonDecode(resData["data"]["lockInfo"] ?? "");
      _electricQuantity = lockInfo["electricQuantity"] ?? widget.info["electricQuantity"];
    });
    EasyLoading.showToast("操作成功");
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      Map lockInfo = jsonDecode(widget.info["lockInfo"] ?? "");
      _electricQuantity = lockInfo["electricQuantity"] ?? 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "电量",
      child: ListView(
        padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
        children: [
          Padding(
            padding: EdgeInsets.only(top: 60),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("电量：", style: TextStyle(fontSize: 24, fontWeight: FontWeight.w500),),
                Text("$_electricQuantity%", style: TextStyle(fontSize: 24, fontWeight: FontWeight.w500),),
              ],
            )
          ),
          const SizedBox(height: 24,),
          const Text("电量信息可以通过网关远程更新，或通过手机蓝牙在锁旁边更新", style: TextStyle(color: ThemeVars.colorTextTer),),
          Padding(
            padding: const EdgeInsets.only(top: 64),
            child: Button(
              onPressed: () {
                _refresh();
              },
              child: const Text("更新",),
            ),
          )
        ],
      ),
    );
  }

}